//
//  OrdersDetailViewController.m
//  hospitalVIP
//
//  Created by Xiaoyan on 13-4-23.
//  Copyright (c) 2013年 MEETStudio. All rights reserved.
//

#import "OrdersDetailViewController.h"

static ASIHTTPConnection *sendOrder_connect;
static ASIHTTPConnection *orderDetail_connect;


@interface OrdersDetailViewController (){
    
    NSDictionary *orderDict;
}

@end

@implementation OrdersDetailViewController


- (void)dealloc{
    
    if (sendOrder_connect != nil) {
        sendOrder_connect.connectionDelegate = nil;
        [sendOrder_connect release];
        sendOrder_connect = nil;
    }
    
    
    if ( orderDetail_connect != nil) {
        orderDetail_connect.connectionDelegate = nil;
        [orderDetail_connect release];
        orderDetail_connect = nil;
    }
    
    [weightLable release];
    [bloodLable release];
    [shuzhangLable release];
    [shousuoLable release];
    [uriProtenLable release];
    
    
    
    [super dealloc];
}


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (id)initWithOrderDict:(NSDictionary *)dict{
    
    self = [super init];
    if (self) {
        
        
        orderDict = dict;
        
    }
    return self;
    
    
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [self initGrowingTextView ];
   
    [self.navigationController.navigationBar setTintColor:[UIColor blackColor]];
    
    if(self){
		[[NSNotificationCenter defaultCenter] addObserver:self
												 selector:@selector(keyboardWillShow:)
													 name:UIKeyboardWillShowNotification
												   object:nil];
		
		[[NSNotificationCenter defaultCenter] addObserver:self
												 selector:@selector(keyboardWillHide:)
													 name:UIKeyboardWillHideNotification
												   object:nil];
	}

    //
    
   
    weightLable.text = [NSString stringWithFormat:@"体重：%@Kg",[orderDict objectForKey:@"Weight"]];
    
    bloodLable.text = [NSString stringWithFormat:@"血糖：%@mmol/L",[orderDict objectForKey:@"BloodSugar"]];
    
    shuzhangLable.text = [NSString stringWithFormat:@"舒张压：%@mmol/L",[orderDict objectForKey:@"DiastolicPressure"]];
    
    shousuoLable.text = [NSString stringWithFormat:@"收缩压：%@mmol/L",[orderDict objectForKey:@"SystolicPressure"]];
    
    uriProtenLable.text = [NSString stringWithFormat:@"尿蛋白：%@mg/L",[orderDict objectForKey:@"UriaProtein"]];
    
       
     self.title = [NSString stringWithFormat:@"%@",[orderDict objectForKey:@"DataUploadTime"]];

    UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithTitle:@"移交中心" style:UIBarButtonSystemItemDone target:self action:@selector(sendToCenter:)];
    
    [self.navigationItem setRightBarButtonItem:rightButton];
    [rightButton release];
    
    [self loadDetail];
    
}


- (void)sendToCenter:(id)sender{
    
    NSString *urlString = [NSString stringWithFormat:@"%@/MobileHealth/TransferToConterAction.aspx?DataID=%@",BASEURL,[orderDict objectForKey:@"DataID"]];
	NSURL *url = [NSURL URLWithString:urlString];
    
    
    if (sendOrder_connect != nil) {
        sendOrder_connect.connectionDelegate = nil;
        [sendOrder_connect release];
        sendOrder_connect = nil;
    }
    
    sendOrder_connect = [[ASIHTTPConnection alloc] initGETWithURL:url resultDict:YES isCache:YES];
    sendOrder_connect.connectionDelegate = self;
    
    [sendOrder_connect startAsynchronous];

    
}

- (void)loadDetail{
    
    
    NSString *urlString = [NSString stringWithFormat:@"%@/MobileHealth/OrderDetailDataAction.aspx?DataID=%@",BASEURL,[orderDict objectForKey:@"DataID"]];
	NSURL *url = [NSURL URLWithString:urlString];
    
    
    if (orderDetail_connect != nil) {
        orderDetail_connect.connectionDelegate = nil;
        [orderDetail_connect release];
        orderDetail_connect = nil;
    }
    
    orderDetail_connect = [[ASIHTTPConnection alloc] initGETWithURL:url resultDict:YES isCache:YES];
    orderDetail_connect.connectionDelegate = self;
    
    [orderDetail_connect startAsynchronous];

    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


-(IBAction)backGroundTap:(id)sender{
    
    [textView resignFirstResponder];
    //[self.inputVIew setFrame:CGRectMake(0, 420, 320, 40)];
    
}


#pragma mark--
#pragma  mark GroingTextView methord

- (void)initGrowingTextView{
    
    containerView = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height -50, 320, 50)];
    //
    containerView.backgroundColor = [UIColor redColor];
    
    
	textView = [[HPGrowingTextView alloc] initWithFrame:CGRectMake(5, 10, 248, 50)];
    textView.contentInset = UIEdgeInsetsMake(0, 5, 0, 5);
    
	textView.minNumberOfLines = 1;
	textView.maxNumberOfLines = 6;
	textView.returnKeyType = UIReturnKeyDefault; //just as an example
	textView.font = [UIFont systemFontOfSize:15.0f];
	textView.delegate = self;
    textView.internalTextView.scrollIndicatorInsets = UIEdgeInsetsMake(5, 0, 5, 0);
    
    
    textView.backgroundColor = [UIColor whiteColor];
    
    // textView.text = @"test\n\ntest";
	// textView.animateHeightChange = NO; //turns off animation
    
    
    [self.view insertSubview:containerView atIndex:100];
	
    UIImage *rawEntryBackground = [UIImage imageNamed:@"MessageEntryInputField.png"];
    UIImage *entryBackground = [rawEntryBackground stretchableImageWithLeftCapWidth:13 topCapHeight:22];
    UIImageView *entryImageView = [[[UIImageView alloc] initWithImage:entryBackground] autorelease];
    //entryImageView.frame = CGRectMake(5, 0, 248, 40);
    
    entryImageView.frame = CGRectMake(5, 0, 248, 50);
    entryImageView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    
    UIImage *rawBackground = [UIImage imageNamed:@"MessageEntryBackground.png"];
    UIImage *background = [rawBackground stretchableImageWithLeftCapWidth:13 topCapHeight:22];
    UIImageView *imageView = [[[UIImageView alloc] initWithImage:background] autorelease];
    imageView.frame = CGRectMake(0, 0, containerView.frame.size.width, containerView.frame.size.height);
    imageView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    
    textView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    
    // view hierachy
    [containerView addSubview:imageView];
    [containerView addSubview:textView];
    [containerView addSubview:entryImageView];
    
    //发送
    UIImage *sendBtnBackground = [[UIImage imageNamed:@"MessageEntrySendButton.png"] stretchableImageWithLeftCapWidth:13 topCapHeight:0];
    UIImage *selectedSendBtnBackground = [[UIImage imageNamed:@"MessageEntrySendButton.png"] stretchableImageWithLeftCapWidth:13 topCapHeight:0];
    
	UIButton *doneBtn = [UIButton buttonWithType:UIButtonTypeCustom];
	doneBtn.frame = CGRectMake(containerView.frame.size.width - 69, 12, 63, 27);
    doneBtn.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin;
	[doneBtn setTitle:@"发送" forState:UIControlStateNormal];
    
    [doneBtn setTitleShadowColor:[UIColor colorWithWhite:0 alpha:0.4] forState:UIControlStateNormal];
    doneBtn.titleLabel.shadowOffset = CGSizeMake (0.0, -1.0);
    doneBtn.titleLabel.font = [UIFont boldSystemFontOfSize:18.0f];
    
    [doneBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
	[doneBtn addTarget:self action:@selector(resignTextView) forControlEvents:UIControlEventTouchUpInside];
    [doneBtn setBackgroundImage:sendBtnBackground forState:UIControlStateNormal];
    [doneBtn setBackgroundImage:selectedSendBtnBackground forState:UIControlStateSelected];
	[containerView addSubview:doneBtn];
    
    
    containerView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
    
    
}

-(void)resignTextView
{
        
      
	[textView resignFirstResponder];
    
    [self sendOrder:textView.text];
    
    textView.text = @"";
    
}

- (void)sendOrder:(NSString *)body{
    
    CLog(@"send Order");
    [LoadingView showDefaultLoadingView];
    
    NSString *urlString = [NSString stringWithFormat:@"%@/MobileHealth/SaveOrderAction.aspx",BASEURL];
    
	NSURL *url = [NSURL URLWithString:urlString];
    
    NSString *doctorId = [[NSUserDefaults standardUserDefaults] valueForKey:USER_ID];
    NSString *name = [[NSUserDefaults standardUserDefaults] valueForKey:USER_NAME];
    NSString *dataId = [orderDict objectForKey:@"DataID"];
    
    NSArray *keys = [NSArray arrayWithObjects:@"Orders",@"DataID",@"DoctorID",@"DoctorName" ,nil];
    
    NSArray *objects = [NSArray arrayWithObjects:body,dataId,doctorId,name, nil];
    
    NSDictionary *theRequestDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
    
    NSString *theBodyString = [[CJSONSerializer serializer] serializeDictionary:theRequestDictionary];
    
    CLog(@"theBodyString  %@", theBodyString);
    
    //  //
    NSData *_jsonData = [theBodyString dataUsingEncoding:NSUTF8StringEncoding];
    
    if (sendOrder_connect != nil) {
        sendOrder_connect.connectionDelegate = nil;
        [sendOrder_connect release];
        sendOrder_connect = nil;
    }
    
    sendOrder_connect = [[ASIHTTPConnection alloc] initPOSTWithURL:url jsonData:_jsonData];
    sendOrder_connect.connectionDelegate = self;
    
    [sendOrder_connect startAsynchronous];

    
    
}


- (void)requestFailed:(ASIHTTPConnection *)connection error:(NSError *)error URL:(NSURL *)url info:(NSDictionary *)info{
    
    
    
}

- (void)requestFinished:(ASIHTTPConnection *)connection resultDict:(NSDictionary *)dict URL:(NSURL *)url info:(NSDictionary *)info{
    
    CLog(@"return dict = %@",dict);
    
    NSString *urlStr = [url absoluteString];
    NSRange range = [urlStr rangeOfString:@"SaveOrderAction.aspx"];
    if (range.length > 0) {
        
        if (dict) {
            
            BOOL issuccess =[[dict objectForKey:@"isSuccess"] boolValue];
            
            if (issuccess) {
                
                [LoadingView showDurationMessageLoadingViewWith:1 message:@"医嘱发送成功"];
                
                [self.navigationController popViewControllerAnimated:YES];
            }
        }

    }
    
    
       range = [urlStr rangeOfString:@"TransferToConterAction.aspx"];

if(range.length > 0){
    BOOL issuccess =[[dict objectForKey:@"isSuccess"] boolValue];
    
    if (issuccess) {

    [LoadingView showDurationMessageLoadingViewWith:2 message:@"移交成功"];
    }
}
      
}



//Code from Brett Schumann
-(void) keyboardWillShow:(NSNotification *)note{
    // get keyboard size and loctaion
	CGRect keyboardBounds;
    backGoundButton.hidden = NO;
    [[note.userInfo valueForKey:UIKeyboardFrameEndUserInfoKey] getValue: &keyboardBounds];
    NSNumber *duration = [note.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSNumber *curve = [note.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey];
    
    // Need to translate the bounds to account for rotation.
    keyboardBounds = [self.view convertRect:keyboardBounds toView:nil];
    
   
    
	// get a rect for the textView frame
	CGRect containerFrame = containerView.frame;
    
    containerFrame.origin.y = CGRectGetHeight(self.view.frame) - (keyboardBounds.size.height + containerFrame.size.height);
    
	// animations settings
	[UIView beginAnimations:nil context:NULL];
	[UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:[duration doubleValue]];
    [UIView setAnimationCurve:[curve intValue]];
	
	// set views with new info
	containerView.frame = containerFrame;
	
       
	// commit animations
	[UIView commitAnimations];
    
    //backGround button
    
    backGoundButton.hidden = NO;
    backGoundButton.userInteractionEnabled = YES;
    [self.view bringSubviewToFront:backGoundButton];
    
}

-(void) keyboardWillHide:(NSNotification *)note{
    
    backGoundButton.hidden = YES;
    
    NSNumber *duration = [note.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSNumber *curve = [note.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey];
	
	// get a rect for the textView frame
	CGRect containerFrame = containerView.frame;
    containerFrame.origin.y = CGRectGetHeight(self.view.frame) - containerFrame.size.height;
    
    // containerFrame.origin.y = 380;
	
	// animations settings
	[UIView beginAnimations:nil context:NULL];
	[UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:[duration doubleValue]];
    [UIView setAnimationCurve:[curve intValue]];
    
	// set views with new info
	containerView.frame = containerFrame;
	
       
	// commit animations
	[UIView commitAnimations];
    
    //backGroundButton
    backGoundButton.hidden = YES;
    backGoundButton.userInteractionEnabled = NO;
    
}

- (void)growingTextView:(HPGrowingTextView *)growingTextView willChangeHeight:(float)height
{
    float diff = (growingTextView.frame.size.height - height);
    
	CGRect r = containerView.frame;
    r.size.height -= diff;
    r.origin.y += diff;
	containerView.frame = r;
}



@end
